package router_group.adaptive

import akka.actor.{Actor, ActorSystem, Props}
import akka.cluster.Cluster
import com.typesafe.config.ConfigFactory
import router_group.{CalcRouter, Calculator}
import router_group.Messages._

import scala.concurrent.duration._
import scala.util.Random
/**
 * @Description: TODO
 * @Author: DJJ
 * @Date: 2019/12/16 13:56
 */
class RouterRunner extends Actor {
  val jobs = List(Add,Sub,Mul,Div)
  import context.dispatcher

  val calcRouter = context.actorOf(CalcRouter.props,"adaptive")
  context.system.scheduler.schedule(3.seconds, 3.seconds, self, "DoRandomMath")

  override def receive: Receive = {
    case  _ => calcRouter ! anyMathJob
  }
  def anyMathJob: MathOps =
    jobs(Random.nextInt(4))(Random.nextInt(100), Random.nextInt(100))
}

object AdaptiveRouterDemo extends App {

  Calculator.create(2551)   //seed-node
  Calculator.create(0)      //backend node

  Thread.sleep(2000)


  val config = ConfigFactory.parseString("akka.cluster.roles = [frontend]").
    withFallback(ConfigFactory.load("adaptive"))

  val calcSystem = ActorSystem("calcClusterSystem",config)

  //#registerOnUp
  Cluster(calcSystem) registerOnMemberUp {
    val _ = calcSystem.actorOf(Props[RouterRunner],"frontend")
  }
  //#registerOnUp

  //val _ = calcSystem.actorOf(Props[RouterRunner],"frontend")

}
